package handle.functions;

import java.security.*;
import java.util.Arrays;


public class SignUtil {
	private static String token = "weixin";
	
	public static boolean checkSign(String sign, String timestamp, String nonce){
		String[] paramArr = new String[]{token, timestamp, nonce};
		//a-b-c-d----z
		Arrays.sort(paramArr);
		//add
		String contentString = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
		String ciphertextString = null;
		
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			//sha-1
			byte[] digest = md.digest(contentString.getBytes());
			ciphertextString = biteToString(digest);
		} catch (Exception e) {
			// 
		}
		return ciphertextString != null ? ciphertextString.equals(sign.toUpperCase()):false;
	}
	
	public static String biteToString(byte[] byteString){
		String xString = "";
		for(int i = 0; i<byteString.length; i++){
			xString += byteToHex(byteString[i]);
		}
		return xString;
	}
	
	public static String byteToHex(byte mbyte){
		char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mbyte>>>4)&0x0F];
		tempArr[1] = Digit[mbyte & 0x0F];
		return new String(tempArr);
	}
}
